package com.amsp.oa.oademo.controller;

import com.amsp.oa.oademo.entity.LeaveApplication;
import com.amsp.oa.oademo.service.LeaveApplicationService;
import com.amsp.oa.oademo.utils.DateUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/leave-application")
@Api(tags = "请假申请接口")
public class LeaveApplicationController {

    private static final Logger logger = LoggerFactory.getLogger(LeaveApplicationController.class);

    @Autowired
    private LeaveApplicationService leaveApplicationService;

    @Autowired
    private ObjectMapper objectMapper;  // 注入配置好的 ObjectMapper

    @PostMapping("/save")
    @ApiOperation("新增请假申请")
    public ResponseEntity<LeaveApplication> save(@RequestBody LeaveApplication leaveApplication) {
        try {
            logger.info("Received leave application: \n{}", 
                objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(leaveApplication));

            // 检查申请编号是否已存在
//            if (leaveApplicationService.checkNoExists(leaveApplication.getNo())) {
//                return ResponseEntity.badRequest()
//                    .header("X-Error-Message", "申请编号已存在")
//                    .build();
//            }

            // 验证日期时间字段
            if (leaveApplication.getPlannedStartTime() == null) {
                logger.warn("PlannedStartTime is null");
                return ResponseEntity.badRequest()
                    .header("X-Error-Message", "计划开始时间不能为空")
                    .build();
            }
            if (leaveApplication.getPlannedEndTime() == null) {
                logger.warn("PlannedEndTime is null");
                return ResponseEntity.badRequest()
                    .header("X-Error-Message", "计划结束时间不能为空")
                    .build();
            }

            if (leaveApplication.getId() != null) {
                throw new RuntimeException("新增时不应该包含ID");
            }
            
            // 添加日期时间格式验证
            try {
                LocalDateTime.parse(leaveApplication.getPlannedStartTime().toString());
                LocalDateTime.parse(leaveApplication.getPlannedEndTime().toString());
            } catch (Exception e) {
                logger.error("Date time parse error", e);
                return ResponseEntity.badRequest()
                    .header("X-Error-Message", "日期时间格式不正确")
                    .build();
            }
            leaveApplication.setNo(DateUtils.getCurrentDateTime());
            leaveApplicationService.save(leaveApplication);
            return ResponseEntity.ok(leaveApplication);
        } catch (Exception e) {
            logger.error("Error saving leave application", e);
            String errorMessage = e.getMessage() != null ? e.getMessage() : "保存失败";
            logger.error("Save failed: {}", errorMessage, e);
            return ResponseEntity.badRequest()
                .header("X-Error-Message", errorMessage)
                .build();
        }
    }

    @PutMapping("/update")
    @ApiOperation("更新请假申请")
    public ResponseEntity<LeaveApplication> update(@RequestBody LeaveApplication leaveApplication) {
        if (leaveApplication.getId() == null) {
            throw new RuntimeException("更新时ID不能为空");
        }
        leaveApplicationService.updateById(leaveApplication);
        return ResponseEntity.ok(leaveApplication);
    }

    @GetMapping("/list")
    @ApiOperation("获取请假申请列表")
    public ResponseEntity<IPage<LeaveApplication>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String employeeId,
            @RequestParam(required = false) String leaveType) {
        try {
            logger.info("Fetching leave applications with params: current={}, size={}, name={}, employeeId={}, leaveType={}", 
                current, size, name, employeeId, leaveType);
            
            IPage<LeaveApplication> page = leaveApplicationService.getPage(current, size, name, employeeId, leaveType);
            
            logger.info("Found {} records", page.getTotal());
            return ResponseEntity.ok(page);
        } catch (Exception e) {
            logger.error("Error fetching leave applications", e);
            return ResponseEntity.badRequest()
                .header("X-Error-Message", "获取列表失败：" + e.getMessage())
                .build();
        }
    }

    @GetMapping("/{id}")
    @ApiOperation("获取请假申请详情")
    public ResponseEntity<LeaveApplication> getById(@PathVariable Long id) {
        return ResponseEntity.ok(leaveApplicationService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除请假申请")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        leaveApplicationService.removeById(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/process/{id}")
    @ApiOperation("获取请假申请流程")
    public ResponseEntity<Map<String, Object>> getProcessById(@PathVariable Long id) {
        try {
            LeaveApplication leaveApplication = leaveApplicationService.getById(id);
            if (leaveApplication == null) {
                logger.warn("Leave application not found with id: {}", id);
                return ResponseEntity.notFound().build();
            }

            // 构建流程数据
            Map<String, Object> processData = new HashMap<>();
            List<Map<String, Object>> steps = new ArrayList<>();

            // 发起申请步骤（使用实际请假数据）
            Map<String, Object> applyStep = new HashMap<>();
            applyStep.put("title", "发起申请");
            applyStep.put("status", "completed");
            applyStep.put("approver", leaveApplication.getName());
            applyStep.put("time", leaveApplication.getCreateTime());
            applyStep.put("comment", String.format("请假%s天，原因：%s", 
                leaveApplication.getPlannedDays(), 
                leaveApplication.getReason()));
            steps.add(applyStep);

            // 添加后续审批步骤（测试数据）
            steps.add(createStep("直接主管审批", "pending", "张经理", null, "等待审批"));
            steps.add(createStep("部门经理审批", "pending", "李总监", null, "等待审批"));
            steps.add(createStep("人事审批", "pending", "王人事", null, "等待审批"));
            steps.add(createStep("总经理审批", "pending", "赵总", null, "等待审批"));

            processData.put("steps", steps);
            return ResponseEntity.ok(processData);
        } catch (Exception e) {
            logger.error("Error getting process data for id: " + id, e);
            return ResponseEntity.status(500).build();
        }
    }

    private Map<String, Object> createStep(String title, String status, String approver, LocalDateTime time, String comment) {
        Map<String, Object> step = new HashMap<>();
        step.put("title", title);
        step.put("status", status);
        step.put("approver", approver);
        step.put("time", time);
        step.put("comment", comment);
        return step;
    }
}